package com.jlastu.znb.presenter;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.jlastu.znb.contract.AddNewsContract;
import com.jlastu.znb.entity.News;
import com.jlastu.znb.entity.NewsPhoto;

import java.util.ArrayList;
import java.util.List;

public class AddNewsPresenter implements AddNewsContract.IAddNewsPresenter {

   private AddNewsContract.IAddNewsView mAddNewsView;
   private Context mContext;

   public AddNewsPresenter(AddNewsContract.IAddNewsView addNewsView, Context context) {
      mAddNewsView = addNewsView;
      mContext = context;
   }
   @Override
   public void saveNews(News news) {
      new Thread(new Runnable() {
         @Override
         public void run() {
            // 插入新闻数据
            ContentValues newsCv = new ContentValues();
            newsCv.put("title", news.getTitle());
            newsCv.put("subtitle", news.getSubtitle());
            newsCv.put("category", news.getCategory());
            newsCv.put("date", news.getDate());
            Uri newsUrl = Uri.parse("content://com.jlastu.znb.provider/news");
            Uri insertUri = mContext.getContentResolver().insert(newsUrl, newsCv);
            long newRowId = ContentUris.parseId(insertUri);
            Log.d("", "新插入的新闻id ===== " + newRowId);

            // 准备批量插入图片数据
            List<NewsPhoto> photoList = news.getPhotoList();
            ContentValues[] arrayValues = new ContentValues[photoList.size()];

            for (int i = 0; i < photoList.size(); i++) {
               ContentValues photoCv = new ContentValues();
               photoCv.put("news_id", newRowId); // 关联新闻ID
               photoCv.put("image", photoList.get(i).getData()); // 图片数据
               // 检查并移除键或值为null的条目
               for (String key : new ArrayList<>(photoCv.keySet())) {
                  if (key == null || photoCv.getAsString(key) == null) {
                     photoCv.remove(key);
                  }
               }
               arrayValues[i] = photoCv;
               Log.d("", "arrayValues ===== " + news);
            }

            // 执行批量插入
            Uri photoUrl = Uri.parse("content://com.jlastu.znb.provider/newsphoto");
            int count = mContext.getContentResolver().bulkInsert(photoUrl, arrayValues);
            Log.d("", "count ===== " + count);
         }
      }).start();
   }
   @Override
   public void showClassPicker() {
      mAddNewsView.showClassPickerDialog(); // 调用视图的回调方法
   }
}
